package at.codejedi.sto.gui.lazy;

import java.awt.Component;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;

import javax.swing.JPanel;

public abstract class LazyPanel extends JPanel implements ILazyView {

	private static final long serialVersionUID = 6540237030480018769L;

	private boolean wasAlreadyDisplayed;

	public LazyPanel() {
		addListener();
	}
	
	private void addListener() {
		addContainerListener(new ContainerListener() {

			@Override
			public void componentAdded(ContainerEvent e) {
				Component c = e.getComponent();
				c.setVisible(false);
				c.setVisible(true);
			}

			@Override
			public void componentRemoved(ContainerEvent e) {
				// TODO Auto-generated method stub

			}
		});
	}

	private void componentInitialized(final ActionListener l) {
		if (wasAlreadyDisplayed)
			return;
		wasAlreadyDisplayed = true;
		l.actionPerformed(null);
	}

	@Override
	public JPanel getPanel(){
		return this;
	}

	@Override
	public void initialLoaded(final ActionListener l) {

		addComponentListener(new ComponentAdapter() {
			@Override
			public void componentShown(ComponentEvent e) {
				componentInitialized(l);
			}

		});

	}

}
